// var HOST = "http://" + document.domain + "/";
var HOST = "http://localhost/rentcar/public/";

layui.use(['element', 'table', 'layer', 'form', 'laydate', 'upload'], function () {
    var element = layui.element;
    var table = layui.table;
    var layer = layui.layer;
    var form = layui.form;
    var laydate = layui.laydate;
    var upload = layui.upload;

    //修改 table 字段
    table.on('edit(edit-table)', function (obj) { //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
        data = obj.data;
        value = obj.value;
        field = obj.field;
        url = $('.edit-table').data('url');
        key = $('.edit-table').data('key');
        $.post(url, {id: data[key], field: field, value: value}, function () {
            data[field] = value;
        })
    });

    //监听工具条
    table.on('tool(edit-table)', function (obj) {
        var data = obj.data;
        var url = $(this).data('url');
        var key = $('.edit-table').data('key');
        var title = $(this).data('title') ? $(this).data('title') : "信息";
        if (obj.event === 'del') {
            layer.confirm('真的要删除吗?', {title: title}, function (index) {
                $.post(url, {id: data[key]}, function (res) {
                    layer.close(index);
                    var msg = res.msg ? res.msg : "网络异常";
                    if (res.code == 200) {
                        obj.del();
                    }
                    layer.msg(msg);
                })
            });
        }
        if (obj.event === 'refuse') {
            layer.confirm('真的拒绝吗?', {title: title}, function (index) {
                $.post(url, {id: data[key]}, function (res) {
                    layer.close(index);
                    var msg = res.msg ? res.msg : "网络异常";
                    if (res.code == 200) {
                        window.location.reload();
                    }
                    layer.msg(msg);
                })
            });
        }
        if (obj.event === 'agree') {
            layer.confirm('真的确定吗?', {title: title}, function (index) {
                $.post(url, {id: data[key]}, function (res) {
                    layer.close(index);
                    var msg = res.msg ? res.msg : "网络异常";
                    if (res.code == 200) {
                        window.location.reload();
                    }
                    layer.msg(msg);
                })
            });
        }
    });
    //监听提交
    $(document).on("submit", ".ajax-form", function (e) {
        var url = $(this).attr("action");
        var method = $(this).attr("method");
        layer.load(); //上传loading
        $.ajax({
            type: method,
            url: url,
            data: $(this).serialize(),
            dataType: 'json',
            success: function (res) {
                layer.closeAll('loading'); //关闭loading
                msg = res.msg ? res.msg : '网络错误';
                icon = res.code == 200 ? 1 : 2;
                jumpUrl = res.jumpUrl;
                layer.msg(res.msg, {icon: icon, time: 1000});
                if (res.code == 200) {
                    if (jumpUrl) {
                        window.location.href = jumpUrl;
                    } else {
                        window.location.reload();
                    }
                }
            },
            error: function (res) {
                layer.closeAll('loading'); //关闭loading
                layer.msg("网络错误");
            }
        });
        return false;
    });

    //监听删除
    $(document).on('click', '.ajax-delete', function (e) {
        e.preventDefault();
        var loading = layer.load(1, {
            shade: [0.1, '#fff'] //0.1透明度的白色背景
        });
        var msg = $(this).data('msg');
        var url = $(this).attr('href');
        var title = $(this).data('title') ? $(this).data('title') : "操作";
        //询问框
        layer.confirm(msg, {
                btn: ['确定', '取消'] //按钮
                , end: function () {
                    layer.close(loading);
                }, title: title
            }, function () {
                $.post(url, '', function (res) {
                    layer.close(loading);
                    icon = res.code == 200 ? 1 : 2;
                    jumpUrl = res.jumpUrl;
                    layer.msg(res.msg, {icon: icon, time: 1000});
                    if (res.code == 200) {
                        if (jumpUrl) {
                            window.location.href = jumpUrl;
                        } else {
                            window.location.reload();
                        }
                    }
                })
            }
        );
    });
    //弹出层
    $(document).on('click', '.model-a', function (e) {
        e.preventDefault();
        var url = $(this).attr('href');
        var title = $(this).data('title') ? $(this).data('title') : "信息";
        $.get(url, {}, function (str) {
            if (str.code == 0) {
                layer.alert('权限不足');
                return;
            }
            layer.open({
                title: title,
                type: 1,
                content: str //注意，如果str是object，那么需要字符拼接。
                , skin: 'min-width-400'
            });
        });
    });

    //执行上传实例单张
    var uploadInst = upload.render({
        elem: '.upload' //绑定元素
        , url: HOST + "master/Common/upload"
        , done: function (res) {
            $(".uploadImg").attr("src", "");
            var s = "<input type='hidden' name='img' value=" + res.data.src + ">";
            $(".uploadDiv").css("display", "inline-block");
            $(".uploadImg").attr("src", res.data.src);
            $(".uploadDiv").append(s);
        }
        , error: function () {
            //请求异常回调
        }
    });

    var uploadInst = upload.render({
        elem: '.uploadz' //绑定元素
        , url: HOST + "master/Common/upload"
        , done: function (res) {
            $(".uploadImgz").attr("src", "");
            var s = "<input type='hidden' name='image' value=" + res.data.src + ">";
            $(".uploadDivz").css("display", "inline-block");
            $(".uploadImgz").attr("src", res.data.src);
            $(".uploadDivz").append(s);
        }
        , error: function () {
            //请求异常回调
        }
    });

    //执行上传实例 多张
     var uploadInst = upload.render({
        elem: '.uploadFile' //绑定元素
        , url: HOST + "master/Common/upload"
        , multiple: true
        , number: 5
        , accept: 'images'
        , size: 0
        , before: function () {
            layer.load(); //上传loading
        }
        , done: function (res) {
            var data = res.data;
            var html = "<div class='addImgDIV'>" +
                "<span class='layui-badge removeBtn addImg'>X</span>" +
                "<img src='" + data.src + "' style='width: 80px;height: 80px;margin: 2px' >" +
                "<input type='hidden' name='attachment[]' value='" + data.src + "'></div>"
            $("#imgDiv").append(html);
            layer.closeAll('loading'); //关闭loading
        }
        , error: function () {
            //请求异常回调
            layer.alert('网络错误,请稍后再试');
            layer.closeAll('loading'); //关闭loading
        }
    });

     //移除图片
    $(document).on("click", ".removeBtn", function () {
        $(this).parent().remove();
        form.render();
    });

     //发送短信
    $(document).on("click", '.sendCode', function (e) {
        var that = $(this);
        var url = $(".url").val();
        var time = 60;
        var type;
        var oldTel = $("#telephone").val();
        e.preventDefault();
        var loading = layer.load(1, {
            shade: [0.1, '#fff'] //0.1透明度的白色背景
        });

        var new_tel = that.parent().siblings().find("input");
        var tel = new_tel.val();
        if (!checkTel(tel)) {
            layer.close(loading);
            layer.msg('手机号格式不正确');
            return;
        }
        if (!tel) {
            layer.close(loading);
            layer.msg('请填写新手机号');
            return;
        }
        if (new_tel.attr("name") == "new_tel") {
            if (oldTel == tel) {
                layer.close(loading);
                layer.msg('新旧账号不能一致');
                return;
            }
            type = 1;
        }
        $.get(url, {telephone: tel, type: type}, function (res) {
            var code = res.code;
            var msg = res.msg;
            layer.close(loading);
            if (code == 200) {
                var interval = setInterval(function () {
                    if (time != 0) {
                        that.attr("disabled", "disabled").addClass("layui-btn-disabled");
                        that.html(time + "s重新发送");
                        time--;
                    } else {
                        clearInterval(interval);
                        that.removeAttr("disabled");
                        that.removeClass("layui-btn-disabled");
                        that.html("重新发送");
                    }
                }, 1000);
            } else {
                layer.close(loading);
                layer.msg(msg);
            }
        })
    })
    $(document).on("click",'.sendcodetwo',function (e) {
        var that = $(this);
        var url = $(".url").val();
        var time = 60;
        var tel = $("#telephone").val();
        e.preventDefault();
        var loading = layer.load(1, {
            shade: [0.1, '#fff'] //0.1透明度的白色背景
        });
        if (!checkTel(tel))  {
            layer.close(loading);
            layer.msg('手机号格式不正确');return;
        }
        if(!tel) {
            layer.close(loading);
            layer.msg('请填写手机号');
            return;
        }
        $.get(url, {telephone: tel}, function (res) {
            var code = res.code;
            var msg = res.msg;
            if(code == 200){
                alert(url);
                layer.close(loading);
                var  interval = setInterval(function () {
                    if(time != 0){
                        that.attr("disabled","disabled").addClass("layui-btn-disabled");
                        that.html(time+"s重新发送");
                        time--;
                    }else{
                        clearInterval(interval);
                        that.removeAttr("disabled");
                        that.removeClass("layui-btn-disabled");
                        that.html("重新发送");
                    }
                },1000);
            }else{
                layer.close(loading);
                layer.msg(msg);
            }
        })
    })
    form.on('switch(switchId)', function(){
        var loading = layer.load(1, {
            shade: [0.1, '#fff'] //0.1透明度的白色背景
        });
        var url = $(this).data('url');
        $.post(url, function (res) {
            layer.close(loading);
            icon = res.code == 200 ? 1 : 2;
            layer.msg(res.msg, {icon: icon, time: 1000});
            if (res.code == 200) {
                window.location.reload();
            }
            layer.msg(msg);
        })
    });
    //商品分类联动
    form.on('select(selectId)', function(data){
        var url = data.elem.id;
        var loading = layer.load(1, {
            shade: [0.1, '#fff'] //0.1透明度的白色背景
        });
        var value = data.value;
        var html="<option value=''>全部</option>";
        if(value){
            $.get(url,{pid:value},function (res) {
                console.log(res);
                var data = res.data;
                var len = res.code;
                for(var i=0;i<len;i++){
                    html +="<option value="+data[i].goods_cate_id+">"+data[i].goods_cate_name+"</option>";
                }
                $("select[name=cate_id]").empty().append(html);
                form.render('select');
            })
        }else {
            $("select[name=cate_id]").empty();
            form.render('select');
        }

        layer.close(loading);
    });

    //检查手机号
    function checkTel($tel) {
        var myreg = /^1[3456789]\d{9}$/;
        if (!myreg.test($tel)) {
            return false;
        } else {
            return true;
        }
    }
    //switch监听
    form.on('switch(switchAjax)', function (data) {
        var url = $(data.elem).data('url');
        $.post(url, {'types': data.elem.checked}, function (res) {

        });
    });


    form.on('select(province)', function (data) {
        var loading = layer.load(1, {
            shade: [0.1, '#fff'] //0.1透明度的白色背景
        });
        var elem = data.elem;
        var url = elem.id;
        var value = data.value;
        var html = "<option value=''>全部</option>";
        if (value) {
            $.get(url, {pid: value}, function (res) {
                var data = res.data;
                var len = res.code;
                $("select[name=area]").empty().append(html);
                for (var i = 0; i < len; i++) {
                    html += "<option value=" + data[i].area_id + ">" + data[i].area_name + "</option>";
                }
                $("select[name=city],select[class=city]").empty().append(html);
                $("select[name=area],select[class=area],tbody[id=table],select[name=school_id]").empty();
                form.render('select');
                layer.close(loading);
            })
        } else {
            $("select[name=city],select[class=city],tbody[id=table],select[name=area],select[class=area],select[name=school_id]").empty();
            form.render('select');
            layer.close(loading);
        }
    });
    form.on('select(city)', function (data) {
        var elem = data.elem;
        var url = elem.id;
        var loading = layer.load(1, {
            shade: [0.1, '#fff'] //0.1透明度的白色背景
        });
        var value = data.value;
        var html = "<option value=''>全部</option>";
        if (value) {
            $.get(url, {pid: value}, function (res) {
                var data = res.data;
                var len = res.code;
                for (var i = 0; i < len; i++) {
                    html += "<option value=" + data[i].area_id + ">" + data[i].area_name + "</option>";
                }
                $("select[name=area],select[class=area]").empty().append(html);
                form.render('select');
                layer.close(loading);
            })
        } else {

            $("select[name=area],select[class=area],tbody[id=table]").empty();
            form.render('select');
            layer.close(loading);
        }
    });
    //监听提交
    form.on('submit(ajax)', function (data) {
        var loading = layer.load(1, {
            shade: [0.1, '#fff'] //0.1透明度的白色背景
        });
        var url = data.form.action;
        var method = data.form.method;
        $.ajax({
            type: method,
            url: url,
            data: data.field,
            dataType: 'json',
            success: function (res) {
                layer.close(loading);
                msg = res.msg ? res.msg : '网络错误';
                layer.msg(msg);
                jumpUrl = res.jumpUrl;
                if (res.code == 200) {
                    if (jumpUrl) {
                        window.location.href = jumpUrl;
                    } else {
                        window.location.reload();
                    }
                }
            },
            error: function (res) {
                layer.close(loading);
                layer.msg("网络错误");
            }
        });
        return false;
    });


    // 单位联动
    form.on('select(where)', function (data) {
        var url = $(data.elem).data('url');
        $.post(url, {pid: data.value}, function (res) {
            var x = ''
            if (res.code == 200) {
                x += '<option value="">请选择部门</option>';
                for (r in res.data) {
                    x += ' <option value="' + res.data[r].company_id + '">' + res.data[r].company_name + '</option>';
                }
            } else {
                x += '<option value="">暂无</option>';
            }
            $('.twhere').html(x);
            form.render();
        })
    });
    form.on('select(twhere)', function (data) {
        var url = $(data.elem).data('url');
        $.post(url, { pid: data.value}, function (res) {
            var x = ''
            if (res.code == 200) {
                x += '<option value="">请选择部门</option>';
                for (r in res.data) {
                    x += ' <option value="' + res.data[r].company_id + '">' + res.data[r].company_name + '</option>';
                }
            } else {
                x += '<option value="">暂无</option>';
            }
            $('.scate').html(x);
            form.render();
        });
    });
    // 品牌联动
    form.on('select(cartype)', function (data) {
        var url = $(data.elem).data('url');
        $.post(url, {pid: data.value}, function (res) {
            console.log(res);
            var x = ''
            if (res.code == 200) {
                x += '<option value="">请选择型号</option>';
                for (r in res.data) {
                    x += ' <option value="' + res.data[r].cartype_id + '">' + res.data[r].cartype_what + '</option>';
                }
            } else {
                x += '<option value="">暂无</option>';
            }

            $('.cartypes').html(x);
            form.render();
        })
    });
    // form.on('select(cartypes)', function (data) {
    //     var url = $(data.elem).data('url');
    //     $.post(url, {pid: data.value}, function (res) {
    //         var x = ''
    //         if (res.code == 200) {
    //             x += '<option value="">请选择型号</option>';
    //             for (r in res.data) {
    //                 x += ' <option value="' + res.data[r].cartype_id + '">' + res.data[r].cartype_what + '</option>';
    //             }
    //         } else {
    //             x += '<option value="">暂无</option>';
    //         }
    //         $('.cartypes').html(x);
    //         form.render();
    //     });
    // });

    //日期选择器
    laydate.render({
        elem: '.laydate-date-one'
        //,type: 'date' //默认，可不填
    });
    //日期选择器
    laydate.render({
        elem: '.laydate-date-two'
        //,type: 'date' //默认，可不填
    });
    //日期选择器
    laydate.render({
        elem: '.laydate-date-three'
        //,type: 'date' //默认，可不填
    });
    //日期选择器
    laydate.render({
        elem: '.laydate-date-four'
        //,type: 'date' //默认，可不填
    });

    //日期选择器
    laydate.render({
        elem: '.laydate-date-start'
        //,type: 'date' //默认，可不填
    });
    //日期选择器
    laydate.render({
        elem: '.laydate-date-end'
        //,type: 'date' //默认，可不填
    });


    //时间选择器
    laydate.render({
        elem: '.laydateTime'
        ,type: 'time'
    });
    //时间选择器
    laydate.render({
        elem: '.laydateTime1'
        ,type: 'time'
    });

});